package metrics

import (
	"sync"
)

type AvgAnalyser struct {
	sync.RWMutex
	name  string
	total float64
	count int
}

var DTSParticipantAvgAnalyser = NewAvgAnalyser("DTS-Participant-Avg-Analyser")

var DTSRegisterTimeCostAvgAnalyser = NewAvgAnalyser("DTS-Register-Time-Cost-Avg-Analyser")
var DTSEnlistTimeCostAvgAnalyser = NewAvgAnalyser("DTS-Register-Time-Cost-Avg-Analyser")
var DTSTryResultReportTimeCostAvgAnalyser = NewAvgAnalyser("DTS-Register-Time-Cost-Avg-Analyser")
var DTSCallbackConfirmTimeCostAvgAnalyser = NewAvgAnalyser("DTS-Callback-Confirm-Time-Cost-Avg-Analyser")
var DTSCallbackCancelTimeCostAvgAnalyser = NewAvgAnalyser("DTS-Callback-Cancel-Time-Cost-Avg-Analyser")

func NewAvgAnalyser(name string) *AvgAnalyser {
	avgAnalyser := &AvgAnalyser{
		name: name,
	}

	return avgAnalyser
}

func (t *AvgAnalyser) IncreaseTotal(increaseNum float64) {
	t.Lock()
	t.total += increaseNum
	t.count++
	t.Unlock()
}

func (t *AvgAnalyser) GetAvgOfIntervalCountingTimeAndReset() float64 {
	t.Lock()

	defer func() {
		t.total = 0
		t.count = 0

		t.Unlock()
	}()

	if t.count > 0 {
		return t.total / float64(t.count)
	} else {
		return 0.0
	}
}
